<!--
    -  Copyright (c) 2018-2025, haohanwork.com All rights reserved.
  -->
<template>
    <div class="execution">
        <basic-container>
            <el-row>
                <el-col :span="6">
                    <el-button type="primary" plain @click="dialogVisible = true">请选择采购单</el-button>
                </el-col>
            </el-row>
            <h2 class="io-goods-detail">
                基础信息
            </h2>
            <el-row class="io-goods-detail basic-information">
                <el-col :span="6">
                    <div class="grid-content bg-purple" v-if="basicInformation.purchaseOrderType == 1">采购类型:采购计划</div>
                    <div class="grid-content bg-purple" v-if="basicInformation.purchaseOrderType == 2">采购类型:按需采购</div>
                    <div class="grid-content bg-purple" v-if="basicInformation.purchaseOrderType == ''">采购类型:</div>
                </el-col>
                <el-col :span="6">
                    <div class="grid-content bg-purple-light">采购商名称:{{basicInformation.checkStatus}}</div>
                </el-col>
                <el-col :span="6">
                    <div class="grid-content bg-purple">原采购单号:{{basicInformation.purchaseSn}}</div>
                </el-col>
                <el-col :span="6">
                    <div class="grid-content bg-purple">配送日期:{{basicInformation.buyFinalTime}}</div>
                </el-col>
            </el-row>
        </basic-container>
        <basic-container>
            <h2 class="io-goods-detail">
                采购退货清单
            </h2>
            <el-table
                    :data="tableData"
                    style="width: 100%"
                    :summary-method="getSummaries"
                    show-summary
                    :header-cell-style="{background:'#eef1f6',color:'#606266'}">
                <el-table-column
                  type="selection"
                  width="100">
                </el-table-column>
                <el-table-column
                        label="序号"
                        prop="id"
                        align="center"
                        type="index">
                </el-table-column>
                <el-table-column
                        label="商品图片"
                        align="center">
                    <template slot-scope="scope">
                        <img :src="scope.row.goodsImg" height="50px"/>
                    </template>
                </el-table-column>
                <el-table-column
                        label="商品"
                        prop="goodsName"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="单位"
                        prop="unit"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="收货数量"
                        prop="needBuyNum"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="收货单价"
                        prop="marketPrice"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="退货数量"
                        prop="realBuyNum"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="退款小计"
                        align="center">
                      <template slot-scope="scope">
                        {{(scope.row.marketPrice * scope.row.needBuyNum).toFixed(2)}}
                      </template>
                </el-table-column>
                <el-table-column
                        label="备注"
                        prop="remarks"
                        align="center">
                    <template v-if="isEdit" slot-scope="scope">
                        <el-input v-model="scope.row.remarks"/>
                    </template>
                </el-table-column>
            </el-table>
            <div style="overflow: hidden;margin-top: 20px;">
              <el-row type="flex" style="float: left;">
                <el-col :span="24">
                  <div>
                    <h3 style="width: 90px;float:left">其它费用:</h3>
                    <template>
                      <el-input v-model="otherAmount" type="number" oninput="if(value.length>8)value=value.slice(0,8)" style="width: 200px"/>
                    </template>
                  </div>
                </el-col>
              </el-row>
              <h3 class="settle-accounts" style="float: right">合计退货金额:{{totalBackAmount.toFixed(2)}}</h3>
            </div>
            <div class="return-btn">
                <template v-if="isEdit">
                    <el-button type="primary" plain @click="backup">保存</el-button>
                </template>
                <el-button type="primary" plain @click="close">返回</el-button>
            </div>
        </basic-container>

        <!--弹窗内容-->
        <el-dialog
                title="请选择一个采购单"
                :visible.sync="dialogVisible"
                width="75%">
            <div>
              <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item>
                  <el-select clearable v-model="formInline.purchaseOrderType">
                    <el-option label="采购计划" value="1"></el-option>
                    <el-option label="按需采购" value="2"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-date-picker type="datetime" v-model="formInline.buyFinalTime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-input placeholder="请输入单号" v-model="formInline.purchaseSn" class="input-with-select">
                      <el-button slot="append" icon="el-icon-search" @click="searchChange"></el-button>
                    </el-input>
                </el-form-item>
              </el-form>
              <!--表格区域-->
              <el-table
                :data="tableData2"
                height="250"
                border
                style="width: 100%">
                <el-table-column
                  prop="purchaseSn"
                  label="采购单号"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="createDate"
                  label="创建时间"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="initiatorId"
                  label="制单人">
                </el-table-column>
                <el-table-column
                  prop="purchaseStatus"
                  label="状态">
                </el-table-column>
                <el-table-column
                  prop="estimateAmount"
                  label="打印次数">
                </el-table-column>
                <el-table-column
                  fixed="right"
                  label="操作"
                  width="150">
                  <template slot-scope="scope">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">选择</el-button>
                  </template>
                </el-table-column>
              </el-table>

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false">取消添加</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<!-- 采购退货 -->
<script>
    import {mapGetters} from 'vuex'
    import {
      fetchList,
      queryList,
      getDetail
    } from '@/api/scm/purchase/purchase_order'
    import {
      addSend
    } from '@/api/scm/purchase/send_back'
    import {getStore, setStore} from "@/util/store";
    import Util from '@/util/pds/utils';
    let cookieUtil = new Util();
    export default {
        name: 'purchase_send_back',
        data() {
            return {
                //弹窗表单
                formInline: {
                  purchaseSn: '',
                  purchaseOrderType:'',
                  buyFinalTime:'',
                },
                // 表格
                tableData: [],
                totalBackAmount: 0,
                basicInformation: {
                  purchaseOrderType:''
                },
                // 是否编辑
                isEdit: true,
                dialogVisible: false,
                tableData2: [],
                page: {
                  total: 0, // 总页数
                  currentPage: 1, // 当前页数
                  pageSize: 20 // 每页显示多少条
                },
                otherAmount:'0',
                tmp:''
            }
        },
        computed: {
          ...mapGetters(['tagWel', 'tagList', 'tag', 'website']),
          tagLen() {
            return this.tagList.length || 0
          }
        },
        created() {
            this.getList();
        },
        methods: {
            //获取采购单
            getList(params) {
              this.tableLoading = true
              fetchList(Object.assign({
                pmId:getStore({name: "pmId"}),
                current: this.page.currentPage,
                size: this.page.pageSize
              }, params)).then(response => {
                this.tableData2 = response.data.data.records
                this.page.total = response.data.data.total
                this.tableLoading = false
              })
            },
            //搜索列表
            searchChange() {
              this.getList(this.filterForm(this.formInline));
            },

            // 数据初始化
            handleClick(row) {
                console.log(row);
                this.tmp = row;
                let params = {
                  purchaseSn: row.purchaseSn,
                  pmId:getStore({name: "pmId"})
                }
                getDetail(params).then(response => {
                  this.dialogVisible = false;
                  this.basicInformation = response.data.data;
                  this.tableData = response.data.data.detailList;
                  response.data.data.detailList.forEach(item =>{
                    this.totalBackAmount += item.needBuyNum*item.marketPrice;
                  });
                })
            },
            // 数据合计
            getSummaries(param) {
                const {columns, data} = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    } else if (index !== 5 && index !== 7) {
                        sums[index] = '';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] = sums[index].toFixed(2);
                    } else {
                        sums[index] = 'N/A';
                    }
                });
                return sums;
            },
            backup: function () {
              let params = {
                returnType:'1',
                detailList:this.tableData,
                otherAmount:this.otherAmount,
                id: this.tmp.id,
                pmId: this.tmp.pmId,
                purchaseOrderType: this.tmp.purchaseOrderType,
                purchaseSn: this.tmp.purchaseSn,
                purchaseStatus:  this.tmp.purchaseStatus,
                reviewType: this.tmp.reviewType,
              };
              addSend(params).then(res=>{
                if(res.code=200){
                  this.$message.success("采购单生成成功");
                  let _this = this;
                  setTimeout(function () {
                    _this.close();
                  },2000)
                }else{
                  this.$message.error("采购单生成失败")
                }
              });
            },
            close(){
              var str_before = location.href.split('#')[1];
              let { tag, key } = this.findTag(str_before);
              this.$store.commit('DEL_TAG', tag);
              this.$router.go(-1);
            },
            findTag(value) {
              let tag, key
              this.tagList.map((item, index) => {
                if (item.value === value) {
                  tag = item
                  key = index
                }
              })
              return { tag: tag, key: key }
            }
        }
    }
</script>

<style lang="scss" scoped>
    .io-goods-detail {
        margin-bottom: 10px;
    }

    .settle-accounts {
        text-align: right;
    }

    .basic-information {
        margin-top: 20px;
        font-weight: inherit;
    }

    .return-btn {
        height: 100px;
        width: 100%;
        text-align: center;
        line-height: 100px;
    }

</style>
